//
//  JWGREditorPic.m
//  koubei
//
//  Created by 李彦宏 on 2018/4/25.
//  Copyright © 2018年 朱圳. All rights reserved.
//

#import "JWGREditorPic.h"
#import <AVFoundation/AVFoundation.h>
#import "JWUserManager.h"
#import "JWGRUsermodel.h"
#import "UIImageView+WebCache.h"
//进度条
#import "MBProgressHUD.h"
static void *ProgressObserverContext = &ProgressObserverContext;

@interface JWGREditorPic ()<UIActionSheetDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UIImagePickerController *picker;
@property (nonatomic, strong) UIImageView *imageV;
@property (nonatomic, strong) JWGRUsermodel *Gmodel;
@property (nonatomic,strong) MBProgressHUD  *HUD;
@end

@implementation JWGREditorPic

- (void)viewDidLoad {
    [super viewDidLoad];
    if(self.picUrl==nil){
       [self.view setBackgroundColor:[UIColor whiteColor]];
        [self settishiUI];
        
    }else{
         [self.view setBackgroundColor:[UIColor blackColor]];
    }
    self.Gmodel=[JWUserManager Gme];

    [self setPicUI];
    //导航栏按钮
    UIImage *image=[UIImage imageNamed:@"更多"];
    //取消渲染
    image=[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
}
-(void)rightBtnClick{
    
    [self ChoosePicture];
    
}

//显示大图UI
-(void)setPicUI{
  _imageV=[[UIImageView alloc]initWithFrame:CGRectMake(0, Navigation_Bar_Height+70, ScreenWidth, ScreenWidth)];
    
    [self UImageV:_imageV imageUrl:self.picUrl];
    
    [self.view addSubview:_imageV];
}
#pragma -mark —————————————————没有图的提示按钮————————————————————
-(void)settishiUI{
    UIButton *bt1=[[UIButton alloc]initWithFrame:CGRectMake(0, Navigation_Bar_Height+30, ScreenWidth, 30)];
    [bt1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [bt1 setBackgroundColor:[UIColor whiteColor]];
    [bt1 setTitle:@"请选择图片上传" forState:UIControlStateNormal];
    [bt1 addTarget:self action:@selector(BtAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bt1];
    
}
-(void)BtAction{
    
    [self ChoosePicture];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)UImageV:(UIImageView *)UImageV imageUrl:(NSString *)imageUrl{
    
    NSString *str=[NSString stringWithFormat:@"%@%@",ImageBaseURL,imageUrl];
    NSLog(@"--str--%@", str);
    str=[str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url=[NSURL URLWithString:str];
    NSLog(@"--url--%@", url);
    UIImage *placeholder=[UIImage imageNamed:@"NoData"];
    [UImageV sd_setImageWithURL:url placeholderImage:placeholder];
}
#pragma -mark —————————————————选择图片————————————————————
-(void)ChoosePicture{
    __block typeof (self) weak_self = self;
    
    _picker = [[UIImagePickerController alloc] init];
    _picker.delegate = self;
    _picker.allowsEditing = YES;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择图片"
                                                                             message:@""
                                                                      preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {}];
    UIAlertAction* fromPhotoAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault                                                                 handler:^(UIAlertAction * action) {
        weak_self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        dispatch_async(dispatch_get_main_queue(), ^{
             [weak_self presentViewController:weak_self.picker animated:YES completion:nil];
        });
        
        NSLog(@"从相册选择");
    }];
    UIAlertAction* fromCameraAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault                                                             handler:^(UIAlertAction * action) {
        NSLog(@"相机");
        
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if(! [UIImagePickerController isSourceTypeAvailable:sourceType]){
            NSString *tips = @"相机不可用";
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:tips preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                NSLog(@"取消");
            }];
            UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                NSLog(@"确定");
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:otherAction];
            [self presentViewController:alertController animated:YES completion:nil];
            return;
        }
        self->_picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:self->_picker animated:YES completion:nil];
        if (![self getCameraRecordPermisson]) {
            NSString *tips = @"请在iPhone的“设置-隐私-相机”中允许访问相机";
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:tips preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                NSLog(@"取消");
            }];
            UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                NSLog(@"确定");
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:otherAction];
            [self presentViewController:alertController animated:YES completion:nil];
            
        }
        
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:fromCameraAction];
    [alertController addAction:fromPhotoAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
    
    
}
#pragma mark UIImagePickerControllerDelegate
//选择图或者拍照后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *orignalImage = [info objectForKey:UIImagePickerControllerOriginalImage];//原图
    UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];//编辑后的图片
    
    _imageV.image=editedImage;
    // 拍照后保存原图片到相册中
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera && orignalImage) {
        UIImageWriteToSavedPhotosAlbum(orignalImage, self, nil, NULL);
    }
    //上传照片
    [picker dismissViewControllerAnimated:YES completion:^{
        if (editedImage) {
            [self doUploadPhoto:editedImage];
        }
    }];
}
//获得设备是否有访问相机权限
-(BOOL)getCameraRecordPermisson
{
    NSString * mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied)
    {
        return NO;
    }
    return YES;
}
-(void)doUploadPhoto:(UIImage *)image{
    
     NSData *fileData = UIImageJPEGRepresentation(image, 1.0);
    if (image == nil) return;
    // 1.创建一个管理者
    if(self.Gmodel.ID==nil){
        self.Gmodel.ID=self.Gmodel.gid;
    }
    if(self.picid==nil){
        self.picid=@"";
    }
     NSLog(@"-->self.picid>a--%@", self.picid);
     NSLog(@"--self.position>>a--%@", self.position);
    NSDictionary *dic=@{@"jwid":JWid,
                        @"jwpassword":JWpassword,
                        @"pid":self.Gmodel.ID,
                        @"position":self.position,
                        @"picid":self.picid,
                        };
      // 2.发送一个请求 url JW_UPGRID
    [self hudTipWillShow:YES];
    [[AFNetworkTool shareManager]upLoadSinglePictureWithUrl:JW_UPGRID parameters:dic fileData:fileData  progerss:^(NSProgress * _Nullable progress) {
        NSLog(@"--progress--%@", progress);
        self.HUD.progress = progress.fractionCompleted;
        
        self->_HUD.labelText = [NSString stringWithFormat:@"%2.f%%",progress.fractionCompleted*100];
     

    } success:^(id  _Nullable json) {
        NSLog(@"--json--%@", json);
        self.picid=json[@"picid"];
       
        [self hudTipWillShow:NO];
    } failure:^(NSError * _Nullable error) {
        NSLog(@"--error--%@", error);
        [MBProgressHUD showError:@"上传失败"];
        [self hudTipWillShow:NO];
    }];
}
#pragma mark -- init MBProgressHUD
- (void)hudTipWillShow:(BOOL)willShow{
    if (willShow) {
        [self resignFirstResponder];
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        if (!_HUD) {
            _HUD = [MBProgressHUD showHUDAddedTo:keyWindow animated:YES];
            _HUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
            _HUD.progress = 0;
            _HUD.labelText = @"0%";
            _HUD.removeFromSuperViewOnHide = YES;
        }else{
            _HUD.progress = 0;
            _HUD.labelText = @"0%";
            [keyWindow addSubview:_HUD];
            [_HUD show:YES];
        }
    }else{
        [_HUD hide:YES];
    }
}




@end
